package com.edu.juc.introduction.tickets;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Seller implements Runnable {
    // 限售量
    private Integer limit;

    private Integer sold = 0;

    private static final Object LOCK = new Object();

    @Override
    public void run() {
        while (Tickets.TICKETS > 0 && sold < limit) {
            synchronized (LOCK) {
                if (Tickets.TICKETS > 0 && sold < limit) {
//                    try {
//                        Thread.sleep(100);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + Tickets.TICKETS + "张票");
                    Tickets.TICKETS--;
                    sold++;
                } else if (sold >= limit) {
                    System.out.println(Thread.currentThread().getName() + "票已售完");
                }
            }
        }
    }

    public Seller(Integer limit) {
        this.limit = limit;
    }
}
